package myschool.util;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author oldliu
 * @since 1.0
 */
public class DbUtil {
    static String classname;//="com.mysql.cj.jdbc.Driver";
    static String url ;//= "jdbc:mysql://localhost:3308/java83?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
    static String user;//="xukang";
    static String pass;//="Xu1234";
    static  {
        //从配置文件读取
        Properties p=new Properties();
        try {
            p.load(DbUtil.class.getClassLoader().getResourceAsStream("db.properties"));
            classname=p.getProperty("classname");
            url=p.getProperty("url");
            user=p.getProperty("username");
            pass=p.getProperty("pass");

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Class.forName(classname);
        } catch (ClassNotFoundException e) {
            System.out.println("无法找到驱动类");
        }
    }
    private DbUtil(){

    }
    //获得数据库连接
    public static Connection get(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, pass);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return connection;
    }
    public static void close(ResultSet rs,Statement st,Connection con){
        close(rs);
        close(st);
        close(con);
    }
    public static void close(PreparedStatement st,Connection con){

        close(st);
        close(con);
    }
    public static void close(ResultSet rs,PreparedStatement st,Connection con){
        close(rs);
        close(st);
        close(con);
    }
    public static void close(Connection con) {
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement st) {
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //关闭资源
    public static void close(ResultSet rs) {
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
